package threadLocal;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
    public static final ThreadLocal<SimpleDateFormat> sdfThreadLocal =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    public static Date parseByThreadLocal(String stringDate) throws Exception {
        return sdfThreadLocal.get().parse(stringDate);
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 3; i++) {
            new Thread(() -> {
                try {
                    System.out.println(DateUtil.parseByThreadLocal("2021-03-30 11:20:30"));

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    DateUtil.sdfThreadLocal.remove();
                    // 手动释放
                }
            }, String.valueOf(i)).start();
        }

    }
}